package com.xpp.yanbi.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 阻塞队列测试
 */
@RestController
@RequestMapping("/queue")
@Slf4j
@Profile({"dev","local"})
public class QueueController {
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     *
     *
     * @param name
     */
    @GetMapping("/add")
    public void add(String name){
        // 使用 CompletableFuture 执行异步操作
        CompletableFuture.runAsync(()->{
            log.info("任务执行中: " + name + ". 执行人: " + Thread.currentThread().getName());
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
            // 异步任务在 ThreadPoolExecutor 执行
        },threadPoolExecutor);
    }

    /**
     * 返回线程池的信息状态
     *
     * @return
     */
    @GetMapping("/get")
    public String  get(){
        Map<String,Object> map = new HashMap<>();
        // 获取线程池的队列长度
        int size  = threadPoolExecutor.getQueue().size();
        map.put("队列长度",size);

        // 获取线程池已接收的任务总数
        long taskCount = threadPoolExecutor.getTaskCount();
        map.put("任务总数",taskCount);

        // 获取线程池已完成的任务数
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        map.put("已完成任务数",completedTaskCount);

        // 获取线程池中正在执行任务的数量
        int activeCount = threadPoolExecutor.getActiveCount();
        map.put("正在工作的线程数",activeCount);

        return JSONUtil.toJsonStr(map);
    }

}
